package com.example.temp.mapper;

import com.example.temp.entity.Result;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Mapper
@Repository
public interface ResultMapper {

    @Select("SELECT * " +
            "FROM results " +
            "WHERE student_id = #{studentId}")
    List<Result> findByStudentId(String studentId);
    
    @Select("SELECT * " +
            "FROM results")
    List<Result> findAll();
    
    @Select("SELECT * FROM results WHERE id = #{id}")
    Result findById(@Param("id") Integer id);
    
    @Insert("INSERT INTO results " +
            "(exam_publish, student_id, question_id, score, start_time, end_time, answer_time, purpose, answer, exam_name) " +
            "VALUES " +
            "(#{examPublish}, #{studentId}, #{questionId}, #{score}, #{startTime}, #{endTime}, #{answerTime}, #{purpose}, #{answer}, #{examName})")
    @Options(useGeneratedKeys = true, keyProperty = "examId")
    void insert(Result result);
    
    @Update("UPDATE results " +
            "SET exam_publish = #{examPublish}, " +
            "score = #{score}, " +
            "start_time = #{startTime}, " +
            "end_time = #{endTime}, " +
            "answer_time = #{answerTime}, " +
            "purpose = #{purpose}, " +
            "answer = #{answer}, " +
            "exam_name = #{examName} " +
            "WHERE exam_publish = #{examPublish} AND student_id = #{studentId} AND question_id = #{questionId}")
    void update(Result result);
    
    @Update("UPDATE results " +
            "SET exam_publish = #{examPublish}, " +
            "score = #{score}, " +
            "start_time = #{startTime}, " +
            "end_time = #{endTime}, " +
            "answer_time = #{answerTime}, " +
            "purpose = #{purpose}, " +
            "answer = #{answer}, " +
            "comment = #{comment} " +
            "WHERE exam_publish = #{examPublish} AND student_id = #{studentId} AND question_id = #{questionId}")
    void updateScoreAndComment(Result result);
    
    // 新增：更新数组中的所有结果
    void update(Result[] results);
    
    // 新增：只更新answer字段
    @Update("UPDATE results " +
            "SET answer = #{answer} " +
            "WHERE id = #{id} " +
            "AND student_id = #{studentId} " +
            "AND question_id = #{questionId}")
    int updateAnswer(Result result);
    
    // 新增：更新answer字段和is_submit字段
    @Update("UPDATE results " +
            "SET answer = #{answer}, is_submit = '1' " +
            "WHERE id = #{id} " +
            "AND student_id = #{studentId} " +
            "AND question_id = #{questionId}")
    int updateAnswerAndSubmit(Result result);
    
    // 新增：只更新score字段
    @Update("UPDATE results " +
            "SET score = #{score} " +
            "WHERE exam_publish = #{examPublish} AND student_id = #{studentId} AND question_id = #{questionId}")
    void updateScore(Result result);
    
    // 新增：只更新comment字段
    @Update("UPDATE results " +
            "SET comment = #{comment} " +
            "WHERE exam_publish = #{examPublish} AND student_id = #{studentId} AND question_id = #{questionId}")
    void updateComment(Result result);
    
    // 新增：更新score、comment和is_correct字段
    @Update("UPDATE results " +
            "SET score = #{score}, comment = #{comment}, is_correct = '1' " +
            "WHERE id = #{id} " +
            "AND student_id = #{studentId} " +
            "AND question_id = #{questionId}")
    int updateScoreCommentAndCorrect(Result result);
    
    @Delete("DELETE FROM results " +
            "WHERE exam_id = #{examId}")
    void delete(Integer examId);
    
//     @Select("SELECT * " +
//             "FROM results " +
//             "WHERE exam_publish = #{examPublish}")
//     List<Result> findByExamPublish(Integer examPublish);
    
    /**
     * 根据examPublish查询所有结果
     */
    @Select("SELECT * FROM results WHERE exam_publish = #{examPublish}")
    List<Result> findByExamPublish(@Param("examPublish") Integer examPublish);
    
    /**
     * 根据examId获取examPublish值
     * @param examId 考试ID
     * @return examPublish值，如果不存在则返回null
     */
//     @Select("SELECT exam_publish " +
//             "FROM results " +
//             "WHERE exam_id = #{examId} " +
//             "LIMIT 1")
//     Integer getExamPublishById(@Param("examId") Integer examId);
    
    /**
     * 根据问题ID列表查询相关的所有测试结果
     * 使用 foreach 来构建 SQL IN 子句
     * @param questionIds 问题ID列表
     * @return 结果列表
     */
    @Select("<script>" +
            "SELECT * " +
            "FROM results " +
            "WHERE question_id IN " +
            "<foreach collection='list' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    List<Result> findByQuestionId(List<Integer> questionIds);

    /**
     * 根据学生ID和测试发布ID获取完整的问题详情
     * 这个方法会关联查询question表获取问题详情
     * @param studentId 学生ID
     * @param examPublish 测试发布ID
     * @return 结果列表，包含完整的问题信息
     */
    @Select("SELECT r.* " +
            "FROM results r " +
            "WHERE r.student_id = #{studentId} AND r.exam_publish = #{examPublish}")
    List<Map<String, Object>> findDetailsByStudentAndExam(@Param("studentId") String studentId, @Param("examPublish") Integer examPublish);

    /**
     * 根据学生ID和测试发布ID获取results表中的记录
     * @param studentId 学生ID
     * @param examPublish 测试发布ID
     * @return results表中的记录
     */
    @Select("SELECT * " +
            "FROM results " +
            "WHERE student_id = #{studentId} AND exam_publish = #{examPublish}")
    @Options(useCache = false)
    List<Result> findResultsByStudentAndExam(@Param("studentId") String studentId, @Param("examPublish") Integer examPublish);

    /**
     * 根据examId, studentId和questionId查询单条记录
     * @param examId 考试ID
     * @param studentId 学生ID
     * @param questionId 问题ID
     * @return 匹配的Result记录，如果不存在返回null
     */
    @Select("SELECT * " +
            "FROM results " +
            "WHERE exam_id = #{examId} AND studentId = #{studentId} AND questionId = #{questionId}")
    Result findByIds(@Param("examId") Integer examId, @Param("studentId") String studentId, @Param("questionId") Integer questionId);

    /**
     * 根据studentId和examPublish查询记录
     * @param studentId 学生ID
     * @param examPublish 考试发布ID
     * @return 匹配的Result记录，如果不存在返回null
     */
    @Select("SELECT * " +
            "FROM results " +
            "WHERE student_id = #{studentId} AND exam_publish = #{examPublish} LIMIT 1")
    Result findByStudentAndExam(@Param("studentId") String studentId, @Param("examPublish") Integer examPublish);

    /**
     * 更新考试截止时间
     * @param examPublish 考试发布ID
     * @param newEndTime 新的截止时间
     * @return 更新的记录数
     */
    @Update("UPDATE results " +
            "SET end_time = #{newEndTime} " +
            "WHERE exam_publish = #{examPublish}")
    int updateExamEndTime(@Param("examPublish") Integer examPublish, @Param("newEndTime") Timestamp newEndTime);
    
    /**
     * 更新考试的答题时间
     * @param examPublish 考试发布ID
     * @param answerTime 新的答题时间（分钟）
     * @return 更新的记录数
     */
    @Update("UPDATE results " +
            "SET answer_time = #{answerTime} " +
            "WHERE exam_publish = #{examPublish}")
    int updateAnswerTime(@Param("examPublish") Integer examPublish, @Param("answerTime") Integer answerTime);

}
